package org.rendao.service
{
	import com.googlecode.flexxb.FlexXBEngine;
	
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.navigateToURL;
	
	import mx.messaging.messages.HTTPRequestMessage;
	import mx.rpc.AsyncToken;
	import mx.rpc.Responder;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.HTTPService;
	import mx.utils.ObjectUtil;
	
	import org.rendao.entity.TBFError;
	import org.rendao.entity.UserDetail;
	import org.rendao.init.AfterLoginHandler;
	import org.rendao.service.base.GlobalModule;
	import org.rendao.service.base.ServiceUtils;

	public class LoginService
	{
		private static var _instance:LoginService;
		
		public static function get instance():LoginService {
			if (!_instance) {
				_instance=new LoginService(new SingletonForcer());
			}
			return _instance;
		}
		
		public function LoginService(sf:SingletonForcer) {
		}
		
		public function login(username:String, password:String, onSuccess:Function, onFault:Function):void {
			var loginSuccess:Function = function(result:Object):void {
				saveCurrentUser(result);
				onSuccess();
			};
			var loginFault:Function = function(error:TBFError):void {
				onFault();
			};
			
			var content:String = username + "," + password;
			ServiceUtils.callService("service/login", loginSuccess, content, onFault);
		}
		
		public function getCurrentUser():void {
			var onFault:Function = function(error:TBFError):void {
				GlobalModule.userDetail = null;
			};
			ServiceUtils.callService("service/get_user", saveCurrentUser, null, onFault);
		}
		
		private static const LOGOUT_URL:String = "/j_spring_security_logout";
		public function logout():void {
			var url:String = GlobalModule.hostUrl + LOGOUT_URL;
			url = url + "?uniqueId=" + new Date().time;
			var request:URLRequest = new URLRequest(url);
			request.method = URLRequestMethod.GET;
			navigateToURL(request, '_self');
		}
		
		private function saveCurrentUser(result:Object):void {
			var resultXml:XML = new XML(result);
			var userDetail:UserDetail = FlexXBEngine.instance.deserialize(resultXml, UserDetail) as UserDetail;
			GlobalModule.userDetail = userDetail;
			new AfterLoginHandler();
		}
	}
}
class SingletonForcer
{
}